<template>
  <div class="products-page">
    <el-header class="header" height="70px">
      <div class="header-content">
        <div class="logo">
          <h1 @click="$router.push('/')" style="cursor: pointer;">周周淘商城</h1>
        </div>
        <div class="search">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品"
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
        <div class="nav-actions">
          <el-button @click="$router.push('/cart')" type="primary" plain>
            <el-icon><ShoppingCart /></el-icon>
            购物车
          </el-button>
          <template v-if="userStore.token">
            <el-dropdown @command="handleUserCommand">
              <el-button type="primary">
                {{ userStore.userInfo?.username || '用户' }}
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template v-else>
            <el-button @click="$router.push('/login')" type="primary">登录</el-button>
            <el-button @click="$router.push('/register')" plain>注册</el-button>
          </template>
        </div>
      </div>
    </el-header>

    <el-main class="main-content">
      <div class="page-header">
        <h2>商品列表</h2>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click="$router.push('/')">首页</el-breadcrumb-item>
          <el-breadcrumb-item>商品列表</el-breadcrumb-item>
        </el-breadcrumb>
      </div>

      <!-- 分类导航 -->
      <div class="category-nav">
        <el-button
          :type="selectedCategory === '' ? 'primary' : 'default'"
          @click="selectCategory('')"
          size="large"
        >
          全部商品
        </el-button>
        <el-button
          v-for="category in categories"
          :key="category"
          :type="selectedCategory === category ? 'primary' : 'default'"
          @click="selectCategory(category)"
          size="large"
        >
          {{ category }}
        </el-button>
      </div>

      <!-- 筛选器 -->
      <div class="filters">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="filters.brand" placeholder="选择品牌" clearable>
              <el-option label="Apple" value="Apple" />
              <el-option label="小米" value="小米" />
              <el-option label="康佳" value="康佳" />
              <el-option label="海尔" value="海尔" />
              <el-option label="TCL" value="TCL" />
              <el-option label="飞利浦" value="飞利浦" />
              <el-option label="姬龙雪" value="姬龙雪" />
              <el-option label="小鹿叮叮" value="小鹿叮叮" />
              <el-option label="纽仕兰" value="纽仕兰" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input-number
              v-model="filters.minPrice"
              placeholder="最低价格"
              :min="0"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="6">
            <el-input-number
              v-model="filters.maxPrice"
              placeholder="最高价格"
              :min="0"
              style="width: 100%"
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 商品列表 -->
      <div class="products-container">
        <el-row :gutter="20">
          <el-col
            v-for="product in products"
            :key="product.id"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
          >
            <el-card
              class="product-card"
              shadow="hover"
              @click="handleProductClick(product)"
            >
              <div class="product-image">
                <img :src="product.image" :alt="product.name">
                <div class="product-overlay">
                  <el-button type="primary" size="small" @click.stop="addToCart(product)">
                    加入购物车
                  </el-button>
                </div>
              </div>
              <div class="product-info">
                <h3 class="product-name">{{ product.name }}</h3>
                <p class="product-brand">{{ product.brand }}</p>
                <div class="product-price">
                  <span class="price">¥{{ formatPrice(product.price) }}</span>
                </div>
                <div class="product-stats">
                  <span class="sold">已售 {{ product.sold }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.pageNo"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[8, 16, 24, 32]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-main>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, ShoppingCart, ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { getItemList, getItemsByCategory, getAllCategories } from '@/api/item'
import { addItem2Cart } from '@/api/cart'
import type { ItemDTO } from '@/api/item'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const searchKeyword = ref('')
const products = ref<ItemDTO[]>([])
const loading = ref(false)
const categories = ref<string[]>([])
const selectedCategory = ref('')

// 格式化价格（将分转换为元）
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2)
}

const filters = reactive({
  brand: '',
  minPrice: null as number | null,
  maxPrice: null as number | null
})

const pagination = reactive({
  pageNo: 1,
  pageSize: 16,
  total: 0
})

// 方法
const handleSearch = () => {
  pagination.pageNo = 1
  loadProducts()
}

const resetFilters = () => {
  Object.assign(filters, {
    brand: '',
    minPrice: null,
    maxPrice: null
  })
  searchKeyword.value = ''
  selectedCategory.value = ''
  handleSearch()
}

const selectCategory = (category: string) => {
  selectedCategory.value = category
  pagination.pageNo = 1
  loadProducts()
}

const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'logout':
      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/')
      break
  }
}

const handleProductClick = (product: ItemDTO) => {
  router.push(`/product/${product.id}`)
}

const addToCart = async (product: ItemDTO) => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  if (!product.id) {
    ElMessage.error('商品信息不完整')
    return
  }

  try {
    await addItem2Cart({
      itemId: product.id as number,
      num: 1,
      name: product.name,
      spec: product.spec || '',
      price: product.price,
      image: product.image
    })
    ElMessage.success('商品已添加到购物车！')
  } catch (error) {
    console.error('添加到购物车失败:', error)
    ElMessage.error('添加到购物车失败')
  }
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageNo = 1
  loadProducts()
}

const handleCurrentChange = (page: number) => {
  pagination.pageNo = page
  loadProducts()
}

// 获取所有分类
const loadCategories = async () => {
  try {
    const response = await getAllCategories()
    const responseData = response.data

    if (responseData && responseData.code === 200 && responseData.data) {
      categories.value = responseData.data
    } else if (responseData && responseData.list) {
      // 兼容旧格式
      categories.value = responseData.list
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 获取商品数据
const loadProducts = async () => {
  try {
    loading.value = true

    const params = {
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      key: searchKeyword.value || undefined,
      brand: filters.brand || undefined,
      minPrice: filters.minPrice || undefined,
      maxPrice: filters.maxPrice || undefined
    }

    let response
    if (selectedCategory.value) {
      // 使用分类查询接口
      response = await getItemsByCategory(selectedCategory.value, params)
    } else {
      // 使用普通查询接口
      response = await getItemList({
        ...params,
        category: undefined
      })
    }

    const responseData = response.data

    if (responseData && responseData.code === 200 && responseData.data) {
      products.value = responseData.data.list || []
      pagination.total = Number(responseData.data.total) || 0
    } else if (responseData && responseData.list) {
      // 兼容旧格式
      products.value = responseData.list || []
      pagination.total = Number(responseData.total) || 0
    } else {
      ElMessage.error((responseData && responseData.msg) || '加载商品失败')
    }
  } catch (error) {
    console.error('加载商品失败:', error)
    ElMessage.error('加载商品失败')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(async () => {
  // 从URL参数获取搜索关键词
  const keyword = route.query.keyword as string
  if (keyword) {
    searchKeyword.value = keyword
  }

  // 从URL参数获取分类
  const category = route.query.category as string
  if (category) {
    selectedCategory.value = category
  }

  // 加载分类和商品
  await loadCategories()
  await loadProducts()
})
</script>

<style scoped>
.products-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo h1 {
  color: #409eff;
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.search {
  flex: 1;
  max-width: 400px;
  margin: 0 40px;
}

.search-input {
  width: 100%;
}

.nav-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 主要内容 */
.main-content {
  flex: 1;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

/* 分类导航 */
.category-nav {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

/* 筛选器 */
.filters {
  background: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-actions {
  margin-top: 15px;
  text-align: center;
}

/* 商品卡片 */
.product-card {
  cursor: pointer;
  transition: transform 0.3s ease;
  margin-bottom: 20px;
}

.product-card:hover {
  transform: translateY(-5px);
}

.product-image {
  position: relative;
  height: 200px;
  overflow: hidden;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-card:hover .product-image img {
  transform: scale(1.05);
}

.product-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.product-card:hover .product-overlay {
  opacity: 1;
}

.product-info {
  padding: 15px;
}

.product-name {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-brand {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.product-price {
  margin-bottom: 10px;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.product-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

/* 分页 */
.pagination {
  margin-top: 40px;
  text-align: center;
}

/* 响应式 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    height: auto;
    padding: 15px 20px;
  }

  .search {
    margin: 15px 0;
    max-width: 100%;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .category-nav {
    justify-content: center;
  }
}
</style>
